package top.surgeqi.security.demo.config.authenticator;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import top.surgeqi.security.demo.bean.po.UserAccount;
import top.surgeqi.security.demo.service.UserAccountService;
import top.surgeqi.security.jwt.config.extend.AbstractPrepareExtendAuthenticator;
import top.surgeqi.security.jwt.config.extend.ExtendAuthenticationEntity;
import top.surgeqi.security.jwt.exception.CustomerAuthenticationException;

/**
 * <p><em>Created by qipp on 2020/5/29 11:28</em></p>
 * 微信授权登录认证器
 * <p>app 进行微信授权登录，通过后会得到用户的微信unionId,
 * 然后通过认证接口将unionId交由此认证器处理即可</p>
 * <blockquote><pre>
 *     注意：目前此示例仅展示微信授权登录的认证过程，与注册流程无关
 * </pre></blockquote>
 *
 * @author <a href="https://gitee.com/qipengpai">qipp</a>
 * @since 1.0.1
 */
@Component
@Slf4j
public class WeChatAuthenticator extends AbstractPrepareExtendAuthenticator {

    /**
     * 微信授权登录认证
     */
    private final static String AUTH_TYPE = "weChat";

    /**
     * 用户账户Service
     */
    private final UserAccountService userAccountService;

    public WeChatAuthenticator(UserAccountService userAccountService) {
        this.userAccountService = userAccountService;
    }

    /**
     * 根据微信unionId方式进行认证
     *
     * @param entity 扩展认证实体
     * @return org.surge.oauth2common.model.UserAccount
     * @author qipp
     */
    @Override
    public UserDetails authenticate(ExtendAuthenticationEntity entity) {
        // 微信unionId
        String unionId = entity.getAuthParameter("unionId");
        if (StringUtils.isEmpty(unionId)) {
            throw new CustomerAuthenticationException("unionId为空！");
        }

        // 根据微信unionId查询用户
        UserAccount userAccount = userAccountService.selectWeChatUnionId(unionId);
        if (null == userAccount) {
            throw new CustomerAuthenticationException("用户不存在！");
        }
        return this.validateAndComposeUser(userAccount);
    }

    /**
     * 微信unionId方式认证
     *
     * @param entity 扩展认证实体
     * @return boolean
     * @author qipp
     */
    @Override
    public boolean support(ExtendAuthenticationEntity entity) {
        return AUTH_TYPE.equals(entity.getAuthType());
    }
}
